#include <iostream>
#include <pthread.h>
#include <unistd.h>
#include <vector>
using namespace std;

//条件变量
pthread_cond_t cond = PTHREAD_COND_INITIALIZER;
//互斥锁
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;

void* MasterCore(void* arg)
{
    sleep(5);   //让所有slaver线程进入条件变量
    cout << "Master thread start work" << endl;
    string name = static_cast<const char*>(arg);
    while (true)
    {
        pthread_cond_signal(&cond);
        sleep(1);
    }
}

void* SlaverCore(void* arg)
{
    string name = static_cast<const char*>(arg);
    //cout << name << " start work" << endl;
    while (true)
    {
        //模拟 工作线程去条件变量中等待
        
        //加锁
        pthread_mutex_lock(&mutex); 
        //进入条件变量队列(假设访问的资源暂时没有了，需要其他线程生产该资源) 为了不重复让一个线程抢占资源，将该线程添加到队列中
        pthread_cond_wait(&cond, &mutex);   //一般条件变量是在加锁和解锁之间的
        //传递互斥锁:让该线程对该锁进行解锁，否则该线程去了队列中，仍然是上锁状态，其他线程也无法访问资源

        //master线程叫醒条件变量中的slaver线程后，就会执行下面的代码
        cout << "当前被叫醒的线程是: " << name << endl;
        //解锁
        pthread_mutex_unlock(&mutex);
    }
}
void StartMaster(vector<pthread_t>& tids)
{
    pthread_t tid = 0;
    int n = pthread_create(&tid, nullptr, MasterCore, (char*)"master");
    if (n == 0)
    {
        cout << "create master success..." << endl;
        tids.emplace_back(tid);
    }
}



void StartSlaver(vector<pthread_t>& tids, int num)
{
    pthread_t tid = 0;
    for (int i = 0; i < num; i++)
    {
        char* name = new char[64];
        snprintf(name, 64, "slaver-%d", i + 1);
        int n = pthread_create(&tid, nullptr, SlaverCore, name);
        if (n == 0)
        {
            cout << "create " << name << " success..." << endl;
            tids.emplace_back(tid);
        }
        //sleep(1);
    }
}

void WaitThreads(vector<pthread_t> tids)
{
    for (auto& tid : tids)
    {
        pthread_join(tid, nullptr);
    }
}
int main()
{
    vector<pthread_t> tids;
    //创建控制线程
    StartMaster(tids);
    //创建工作线程
    StartSlaver(tids,  5);
    //等待所有线程
    WaitThreads(tids);
}